package org.example.supplychain.controller;

import jakarta.servlet.http.HttpSession;
import org.example.supplychain.domain.*;
import org.example.supplychain.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private EntryExitRecordsService entryExitRecordsService;
    @Autowired
    private TotalMaterialService totalMaterialService;
    @Autowired
    private MaterialService materialService;

    @GetMapping("")
    public String home(HttpSession session) {
        List<Order> allOrders = orderService.getAllOrders();

        List<Supplier> suppliers = supplierService.getAllSuppliers();
        List<Inventory> inventories = inventoryService.getAllInventories();

        session.setAttribute("allOrders", allOrders);
        session.setAttribute("suppliers", suppliers);

        session.setAttribute("inventories", inventories);

        return "order";
    }

    @PostMapping("/create")
    public String insert(@RequestParam(value = "materialName") String materialName, @RequestParam(value = "materialNumber") long materialNumber,
                         @RequestParam(value = "price") String price, @RequestParam(value = "deadline") String deadline,
                         @RequestParam(value = "supplierName") String supplierName, HttpSession session) {
        Order order = new Order();
        order.setMaterialName(materialName);
        order.setMaterialNumber(materialNumber);
        order.setPrice(Double.parseDouble(price));
        order.setInventoryName("未入库");
        order.setStatus("进行中");
        order.setStartTime(new Date());
        order.setSupplierName(supplierName);
        order.setBuyerName(session.getAttribute("name").toString());
        order.setAverageUnitPrice(Double.parseDouble(price) / materialNumber);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            order.setDeadline(sdf.parse(deadline));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        orderService.addOrder(order);
        
        List<Material> tmp = materialService.getMaterialByMaterialName(materialName);
        if(tmp!=null){
            for(Material m: tmp){
                if(m.getSupplierName().equals(supplierName)){
                    return "orderManagement";
                }
            }
        }
        Material m = new Material();
        m.setMaterialName(materialName);
        m.setSupplierName(supplierName);
        m.setAverageUnitPrice(Double.parseDouble(price) / materialNumber);
        materialService.addMaterial(m);
        return "orderManagement";
    }


    @PostMapping("/update")
    public String update(@RequestParam(value = "orderId") long orderId, @RequestParam("targetInventory") String targetInventory, Model model) {
        Order order = orderService.getOrderByOrderId(orderId);
        order.setInventoryName(targetInventory);
        order.setStatus("已完成");
        order.setEndTime(new Date());
        orderService.updateOrder(order);
        entryExitRecordsService.addRecord(order.getMaterialName(), order.getMaterialNumber(), "入库", order.getSupplierName(), order.getInventoryName());
        TotalMaterial tmp = totalMaterialService.getTotalMaterialByName(order.getMaterialName());
        if(tmp!=null){
            tmp.setMaterialTotalNumber(tmp.getMaterialTotalNumber() + order.getMaterialNumber());
            totalMaterialService.updateMaterialTotalNumberByMaterialName(tmp);
        }else {
            tmp = new TotalMaterial();
            tmp.setMaterialName(order.getMaterialName());
            tmp.setMaterialTotalNumber(order.getMaterialNumber());
            tmp.setMinimumStock(0);
            tmp.setWarningState(false);
            totalMaterialService.addTotalMaterial(tmp);
        }
        return "orderManagement";
    }

    @GetMapping("/query")
    public String query(HttpSession session) {
        return "orderQuery";
    }

    @PostMapping("/query")
    public String query(@RequestParam(value = "materialName") String materialName, @RequestParam("inventory") String inventory,
                        @RequestParam("status") String status, @RequestParam("start") String start, @RequestParam("end") String end, Model model) {
        List<Order> orderList = orderService.getAllOrders();
        Stream<Order> tmp = orderList.stream();
        if (!materialName.isEmpty()) {
            tmp = tmp.filter(o -> o.getMaterialName().contains(materialName));
        }
        if (!inventory.isEmpty()) {
            tmp = tmp.filter(o -> o.getInventoryName().contains(inventory));
        }
        if (!status.isEmpty()) {
            tmp = tmp.filter(o -> o.getStatus().equals(status));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (!start.isEmpty()) {
            tmp = tmp.filter(e -> {
                try {
                    return e.getStartTime().after(sdf.parse(start));
                } catch (ParseException ex) {
                    throw new RuntimeException(ex);
                }
            });
        }
        if (!end.isEmpty()) {
            tmp = tmp.filter(e -> {
                try {
                    return e.getEndTime().before(sdf.parse(end));
                } catch (ParseException ex) {
                    throw new RuntimeException(ex);
                }
            });
        }
        model.addAttribute("ordersQuery", tmp.toList());
        return "orderQuery";
    }

    @GetMapping("/manage")
    public String manage(HttpSession session) {
        return "orderManagement";
    }

    @GetMapping("/reminder")
    public String reminder(HttpSession session) {
        List<Order> deadlineList = orderService.getOrdersNearDeadline();
        session.setAttribute("deadlineList", deadlineList);
        return "reminderSection";
    }

    @GetMapping("/demand")
    public String demand(HttpSession session) {
        List<TotalMaterial> materialDemandList = orderService.getLackingMaterial();
        session.setAttribute("materialDemandList", materialDemandList);
        return "materialDemand";
    }

    @GetMapping("supplier")
    public String supplier(HttpSession session) {
        List<Supplier> suppliers = supplierService.getAllSuppliers();
        session.setAttribute("suppliers", suppliers);
        return "supplier";
    }
}
